###
	Outline
	
	- Global Vars
	- Core Code (run once)
		-- add table / form
		-- self subscription (duplicate check)
		-- main subscription (fill form)
	- Event Handlers
		-- cancel button
		-- submit button
			-- check duplicate
			-- check invalid fields
			-- doc obj and parse
			-- save doc to couch
				-- publish Donor ID
###

define [
	'jquery'
	'sammy/plugins/sammy.template-0.7.1.min.js'
	'jquery.couch.js'
	'helper'
], ($, undef, undef, H) ->
	S = {}
	$.fn.mb_add_donation = (SamCtx) ->
	
		# --- Global Variables and Function ---------------
		
			$this = $(@)
			_time = ""
			_dID = ""
			S = SamCtx
			savedAmount = ""
			
			# Custom Date() helper function to output ISODate Format (YYYY-MM-DD HH:MM:SS)
			Date.prototype.isoDateTime = () ->
				if @getUTCMonth()+1 < 10 then _month = "0#{@getUTCMonth() + 1}" else _month = @getUTCMonth() + 1
				if @getUTCDate() < 10 then _date = "0#{@getUTCDate()}" else _date = @getUTCDate()
				return "#{@getUTCFullYear()}-#{_month}-#{_date} #{(s = @toTimeString().split('GMT')[0]).slice(0, s.length - 1)}"
			
		# --- Core code of plugin -------------------------
		
			unless @mb_plugin()
				@mb_plugin 'add_donation'

				# Self-subscription of donation ID to retrieve "last-created" donation doc date so that
				# subsequent matching of date can be tested to avoid duplicate donation creation
				$.subscribe "mb.donation", (e, arg) => 
					$.couch.db("vcn-members").openDoc arg['id'],
						{success: (doc) -> _time = doc.donation_date if arg['ok']}
			
				# Main subscription event to handle a donor_id being published from donor_detail		
				$.subscribe "mb.add_donation", (e, arg) => 
					_dID = arg['donor_id']
					type = arg['type']
					
					switch type
						when "ind.b" then amount = "$15.00"
						when "ind.b" then amount = "$25.00"
						when "ind.c" then amount = "$40.00"
						
					# Empty all manually input fields to empty form
					$('[name="donation_amount"], [name="login_id1"], [name="comment"]').val("")
					
					# Display subscribed donor ID
					$('[name="donor_id"]').val(_dID)
				
					# Refresh button updates the time 
					$('#refresh').click () ->
						$('[name="donation_date"]').val(d = ((new Date()).isoDateTime())).html(d)
				
					# Invoke a click on the refresh button to fill out the Donation Date field
					$('#refresh').click()
					
					$('[name="donation_amount"]').val(amount)
					
			


		# --- Button Event Handlers ------------------
		
			$('[name="donation_amount"]').focus ()->
				savedAmount = $(@).val()
				$(@).val($(@).val().replace(/.00/g, "").replace(/[$]/g, ""))

			$('[name="donation_amount"]').blur ()->
				$old_val = $(@).val()
				if $old_val.indexOf(".") isnt -1
					if $old_val.split(".").length > 2 or $old_val.split(".")[1] isnt "00"
						$.publish "mb.msg", {
							msg: "Field value invalid."
							type: "error"
								}
						$(@).val(savedAmount).select()
						return false
				$new_val = "$#{$(@).val().replace(/.00/g, '').replace(/[$]/g, '')}.00"
				$(@).val $new_val
				return			
			# Handle Cancel button click
			$(@).find('input:button[value="Cancel"]').on 'click', ->
				S.setLocation "#/donor_detail"		
			
			# Handle Submit button click
			$(@).find('input:button[value="Submit"]').on 'click', ->
				
				# Check to see for duplicate creation
				if _time isnt ""
					if $("[name='donation_date']").val().toString() is _time.toString()
						$.publish "mb.msg", {
							msg: "Duplicate donation. Refresh Payment Date field to add new donation."
							type: "error"
								}
						return false
				
				# Check to see for empty Donation Amount field
				if $('input[name="donation_amount"]').val().length is 0
					$.publish "mb.msg", {
						msg: "Donation amount field cannot be empty."
						type: "error"
							}
					return false
				
				# Check to see if Donation Amount field isn't a number
				$amount = $('[name="donation_amount"]').val().replace(/.00/g, "").replace(/[$]/g, "")
				if isNaN($amount)
					$.publish "mb.msg", {
						msg: "Donation amount field value is not valid."
						type: "error"
							}
					return false
		
				# Create helper doc object and parse the serializeArray of the form
				doc = new H.doc
				doc.parse($this.find('form').serializeArray())
				doc.cash or= false
				
				# Save object to couch document
				$.couch.db("vcn-members").saveDoc doc,
					{success: (save)->
				
						# Publish donation detail (ie. ID) for donation_detail is subscribed to
						$.publish "mb.donation", save
						
						# Publish to "mb.donor" to let view_receipt know that it should refresh its 
						# record table only when donation has been added successfully
						if save.ok
							$.publish "mb.donor", {donor_id: _dID} 
							S.setLocation "#/donation_detail"
					}
				return false
		return @
	return
